//
//  CurrencyTextFieldEffect.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/4/25.
//

import Foundation
import UIKit

class CurrencyTextFieldEffect: BaseEffect {
    
    var value: String? {
        set {
            valueTF.text = newValue
            ctl.isHidden = value != nil
            isEdited = (newValue == nil || newValue == "") ? false : true
        }
        get {
            return valueTF.text
        }
    }
    
    let valueTF = UITextField()
    
    override func editTapped() {
        super.editTapped()
        valueTF.becomeFirstResponder()
    }
    
    override func setupUI() {
        super.setupUI()
        
        valueTF.textColor = .black
        valueTF.font = UIFont.systemFont(ofSize: 16)
        valueTF.delegate = self
        valueTF.keyboardType = .decimalPad
        insertSubview(valueTF, aboveSubview: keyL)
        valueTF.snp.makeConstraints { (make) -> Void in
            make.height.equalTo(33)
            make.top.equalTo(keyL.snp.bottom)
            make.left.equalTo(self.snp.left).offset(12)
            make.right.equalTo(self.snp.right).offset(-12)
        }
    }
}

// MARK: - UITextFieldDelegate
extension CurrencyTextFieldEffect: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        isEdited = !(textField.text == nil || textField.text == "")
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard string == "." || string == "0" else {
            let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

            let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
            let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
            let numberOfMatches = regex.numberOfMatches(in: newString, options:.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
            return numberOfMatches != 0
        }
        guard let text = textField.text else { return true }
        if text.count == 0 {
            textField.text = "0."
            return false
        }
        if text.range(of: ".") != nil && string == "." {
            return false
        }
        if text.range(of: ".") != nil {
            let list = textField.text!.components(separatedBy: ".")
            let last = list.last!
            return (last as NSString).length < 2
        }
        return true
    }
}
